package com.example.fieldnotes;

import java.io.File;
import java.io.FileInputStream;
import java.util.Iterator;
import java.util.Vector;

import jxl.WorkbookSettings;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Environment;

@SuppressWarnings("unused")
public class dataStuff {
	private String[][] data;
	private String fileName = "";
	private int x, y;
    private SharedPreferences pref;
	private WritableWorkbook workbook;
	private File sdCard = Environment.getExternalStorageDirectory(), file;
	private FileInputStream in;
	private String directory;
	private WritableSheet sheet;
	private WorkbookSettings wbSettings;
	private int option, test = 1;
	private Vector cellVectorHolder;
	private MainActivity mainActivity;
	
	public dataStuff(String[][] data, int x, int y) {
		this.x = x;
		this.y = y + 1;
		this.data = new String[x][y];
		
		for (int i = 0; i < x; i++)
			for (int j = 0; j < y; j++)
				this.data[i][j] = data[i][j];
	}
	
	public dataStuff(SharedPreferences pref, int sizen, int sizem, int option, String newFilename, MainActivity mainActivity)
	{
		this.mainActivity = mainActivity;
		fileName = newFilename;
		this.option = option;
		x = sizen;
		y = sizem + 1;
		data = new String[x][y];
		//System.out.println(x + "::" + y);
        this.pref = pref;
		
		if (option == -1)
		{
			for (int i = 0; i < x; i++)
				for (int j = 0; j < y; j++)
					data[i][j] = "";
		}
		else
		{
			if (option == 0 && fileName.matches(""))
			{
				fileName = "notes.xls";
				
				for (int i = 0; i < x; i++)
					for (int j = 0; j < y; j++)
						data[i][j] = "";
			}
			else if (option == 1 && fileName.matches(""))
			{
				fileName = "rating.xls";
				for (int i = 0; i < x; i++)
					for (int j = 0; j < y; j++)
						data[i][j] = "0";
			}
			else if (option == 2 && fileName.matches(""))
			{
				fileName = "dates.xls";
				
				for(int i = 0; i < x; i++)
					for (int j = 0; j < y; j++)
						data[i][j] = "01/01/1980";
			}
			else if (option == 3 && fileName.matches(""))
				fileName = "";

			
			directory = (sdCard.getAbsolutePath() + "/MAGICStuff/" + fileName);
			if (!isExternalStorageAvailable() || isExternalStorageReadOnly()) 
	        { 
	            System.out.println("Storage not available or read only"); 
	            return; 
	        } 
	 
	        try{
	        	// Creating Input Stream 
	            in = new FileInputStream(directory);
	            
	            Vector cellVectorHolder = new Vector();
	            
	            // Create a POIFSFileSystem object 
	            POIFSFileSystem myFileSystem = new POIFSFileSystem(in);
	            // Create a workbook using the File System 
	            HSSFWorkbook myWorkBook = new HSSFWorkbook(myFileSystem);
	 
	            // Get the first sheet from workbook 
	            HSSFSheet mySheet = myWorkBook.getSheetAt(0);
	            Iterator rowIter = mySheet.rowIterator();
	            
	            while(rowIter.hasNext()){
	                HSSFRow myRow = (HSSFRow) rowIter.next();
	                Iterator cellIter = myRow.cellIterator();
	                Vector cellStoreVector=new Vector();
	                while(cellIter.hasNext()){
	                    HSSFCell myCell = (HSSFCell) cellIter.next();
	                    cellStoreVector.addElement(myCell);
	                }
	                cellVectorHolder.addElement(cellStoreVector);
	            }
	            
                printCellDataToConsole(cellVectorHolder, -1);
                
	          } catch (Exception e) {
	        	  e.printStackTrace();
	          }
		}
	}
	
	public dataStuff(int i, int j) {
		// TODO Auto-generated constructor stub
		data = new String[i][j];
	}

	private void printCellDataToConsole(Vector dataHolder, int row)
	{
		int[] rows;
		int cols = 0;
		
		cols = dataHolder.size();
		rows = new int[cols];
		
		for (int i = 0; i < cols; i++)
		{
			Vector c = (Vector)dataHolder.elementAt(i);
			rows[i] = c.size();
		}
		
		String[][] tempHolder = new String[cols][rows[0]];
		
	    for (int i = 0; i < dataHolder.size(); i++){
	        Vector cellStoreVector=(Vector)dataHolder.elementAt(i);
	        
	        for (int j = 0; j < cellStoreVector.size(); j++){
	            HSSFCell myCell = (HSSFCell)cellStoreVector.elementAt(j);
	            
	            String stringCellValue;
	            if (myCell.toString().contains("."))// >= 3 && (myCell.toString().matches("0.0") || myCell.toString().matches("10.0")))
	            	stringCellValue = myCell.toString().substring(0, myCell.toString().indexOf("."));
	            else
	            	stringCellValue = myCell.toString();
	            
	            tempHolder[i][j] = stringCellValue;
	            //System.out.print(tempHolder[j][i] + ", ");
	        }
	        //System.out.println(x + "x::y" + y);
		    for (int k = 0; k < x; k++)
		    {
		    	for (int j = 0; j < y; j++)
		    	{
		    		try {
		    		if (tempHolder[j][k] != null)
		    			data[k][j] = tempHolder[j][k];
		    		else
		    			break;
		    		} catch (ArrayIndexOutOfBoundsException e) { break; }
		    		System.out.print(data[k][j]);
		    	}
		    	System.out.println();
		    }
		    
	        System.out.println("done");
	    }
	    
	    SharedPreferences.Editor editor = pref.edit();
        editor.putBoolean("loaded", true);
        editor.commit();
	    
	    Intent i = new Intent(mainActivity, MainActivity.class);
	    i.putExtra("size", data.length);
	    
	    for (int j = 0; j < data.length; j++)
	    {
	    	i.putExtra("data" + j, data[j]);
	    }
	    
    	mainActivity.startActivity(i);
    	
	    String temp = data[0][1];
	    
        if (option == 0 && temp.contains("/"))
        	test = -1;
        else if (option == 1 && !temp.contains("/"))
        {
        	try {
        		test = Integer.parseInt(temp);
        	} catch (Exception e) {
        		test = -1;
        	}
        }
        else if (option == 2 && !temp.contains("/"))
        	test = -1;
	}
	
	public String get(int x, int y)
	{
		if (x < this.x)
			return data[x][y];
		else
			return "0";
	}
	
	public void add(int x, int y, String input)
	{
		data[x][y] = input;
	}
	
	public void delete(int x, int y)
	{
		data[x][y] = "";
	}
	
	public int clear()
	{
		for (int i = 0; i < x; i++)
			for (int j = 0; j < y; j++)
				data[i][j] = "";
		return 0;
	}
	
	public static boolean isExternalStorageReadOnly() { 
        String extStorageState = Environment.getExternalStorageState(); 
        if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(extStorageState)) { 
            return true; 
        } 
        return false; 
    } 
 
    public static boolean isExternalStorageAvailable() { 
        String extStorageState = Environment.getExternalStorageState(); 
        if (Environment.MEDIA_MOUNTED.equals(extStorageState)) { 
            return true; 
        } 
        return false; 
    } 
    
    public String[][] getData() {
    	return data;
    }
    
    public void setData(String[][] data, int count, int eRow) {
    	this.data = data;
    	System.out.println("Changed!");
    }
    
    public int isRightFormat()
    {
    	return test;
    }
}